package com.odobenus.client.loader;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

import org.springframework.boot.env.PropertySourceLoader;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import com.odobenus.client.properties.OdobenusProperties;
import com.odobenus.client.tools.BeanUtils;
import com.odobenus.client.tools.PropertiesUtil;

public class PropConfPropertySourceLoader implements PropertySourceLoader {
	public String[] getFileExtensions() {
		return new String[] { "properties" };
	}

	private Map<String, Object> mapPropertySource(Resource resource) throws IOException {
		Map<String, Object> result = (Map) PropertiesLoaderUtils.loadProperties(resource);
		OdobenusProperties odobenusProperties = PropertiesUtil.loadContext();
		if (odobenusProperties.getMode().equals("apollo")) {
			InputStream inputStream = null;
			if (odobenusProperties.getEnableRemote()) {
				inputStream = BeanUtils.downloadFileInputStream(odobenusProperties, "apollo.properties");
			}else {
				inputStream = BeanUtils.loadLocalFileInputStream(odobenusProperties, "apollo.properties");
			}
			result.putAll((Map) PropertiesLoaderUtils.loadProperties(new InputStreamResource(inputStream)));
		}
		
		return result;
	}

	@Override
	public PropertySource<?> load(String name, Resource resource, String profile) throws IOException {
		Map<String, Object> result = mapPropertySource(resource);
		return new RefreshPropertySource(name, result);
	}
}